import urllib.request
import json


# 读取内容的函数
def get_data(url, data=None):
    headers = {  # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0",
        # "Referer": "http://192.168.4.1/",
        # "Accept": "application/json, text/javascript, */*; q=0.01",
        # "X-Requested-With": "XMLHttpRequest",
        # "Content-Type": "application/json; charset=UTF-8"
    }
    # 水星的路由器对请求头验证不是很严格，我把这些都关闭了似乎也一切正常，如果你们有需要自己关闭注释
    data = json.dumps(data).encode("utf-8")
    # data = urllib.parse.urlencode(data)
    # data = data.encode("utf-8")
    req = urllib.request.Request(url, data, headers)
    response = urllib.request.urlopen(req)
    data = response.read()
    response.close()
    return data


if __name__ == "__main__":
    # 获取令牌
    url = "http://192.168.0.1/"  # 路由器ip
    paras = {"method": "Auth", "login": {"password": "MTk4OTAzMQ=="}}  # 密码具体如何加密的不太清楚，我是直接在浏览器上看的
    data = get_data(url, paras).decode()
    stok = json.loads(data).get("stok")

    # 通过stok构造url
    url = "http://192.168.0.1//stok=" + stok + "/ds"
    # 请求参数
    js = {"protocol": {"name": ["pppoe", "wan"]}, "network": {"name": "wan_status"}, "method": "get"}
    data = get_data(url, js)
    # 解析获取的数据，取得ip
    ip = json.loads(data.decode()).get("network").get("wan_status").get("ipaddr")
